package utils

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/go-redis/redis/v8"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var DB *gorm.DB
var Red *redis.Client

const (
	PublishKey = "websocket"
)

// 初始化配置项
func InitConfig() {
	viper.SetConfigName("app")
	viper.AddConfigPath("config")
	viper.SetConfigType("yml")
	err := viper.ReadInConfig()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("config mysql:", viper.Get("mysql"))
	fmt.Println("config redis:", viper.Get("redis"))

}

// 初始化数据库
func InitMySQL() {

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second,
			LogLevel:      logger.Info,
			Colorful:      true,
		},
	)

	DB, _ = gorm.Open(mysql.Open(viper.GetString("mysql.dns")), &gorm.Config{
		Logger:                 newLogger,
		SkipDefaultTransaction: true,
	})
}

// 初始化redis
func InitRedis() {

	Red = redis.NewClient(&redis.Options{
		Addr:     viper.GetString("redis.addr"),
		Password: viper.GetString("redis.password"),
		// DB:           viper.GetInt(viper.GetString("redis.DB")),
		PoolSize:     viper.GetInt(viper.GetString("redis.poolSize")),
		MinIdleConns: viper.GetInt(viper.GetString("redis.minIdleConns")),
	})

	fmt.Println("init redis:", Red)
}

// Publish 发布消息到redis
func Publish(ctx context.Context, channel string, msg string) error {
	fmt.Println("Publish...", msg)
	err := Red.Publish(ctx, channel, msg).Err()
	if err != nil {
		fmt.Println("Publish err", err)
	}
	return err
}

// Subscribe 订阅消息
func Subscribe(ctx context.Context, channel string) (string, error) {
	fmt.Println("Subscribe 订阅消息", ctx)
	sub := Red.Subscribe(ctx, channel)
	fmt.Println("Subscribe sub", sub)
	msg, err := sub.ReceiveMessage(ctx)
	fmt.Println("Subscribe ctx", ctx)
	if err != nil {
		fmt.Println("Subscribe err", err)
		return "----报错啦---", err
	}
	fmt.Println("Subscribe----msg", msg.Payload)
	return msg.Payload, err
}
